package com.softserveinc.lahire.builders;

import com.softserveinc.lahire.handlers.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.util.StringTokenizer;

import org.omg.CORBA.RepositoryIdHelper;

import com.softserveinc.lahire.handlers.Handler;
import com.softserveinc.lahire.handlers.TextHandler;

public class HTTPWorker extends Thread {

	Director director = new Director();
	
	public static ResponseDirector responseDirector = new ResponseDirector();

	HandlersChain chain = new HandlersChain();
	Socket socket;

	public HTTPWorker(Socket socket) {
		this.socket = socket;
	}

	public void run() {

		try {
			InputStream is = socket.getInputStream();
			
			OutputStream out = socket.getOutputStream();

			InputStreamReader inputStreamReader = new InputStreamReader(is);
			BufferedReader in = new BufferedReader(inputStreamReader);

			
			String first = in.readLine();
			// Get path and method
			StringTokenizer tok = new StringTokenizer(first);
			String method = (String) tok.nextElement();
			String path = (String) tok.nextElement();
			
			// Determine and set which builder to use
			if (method.equalsIgnoreCase("GET")) {
				
				director.setRequestBuilder(new GetRequestBuilder());

			}else if (method.equalsIgnoreCase("POST")){
				
				director.setRequestBuilder(new PostRequestBuilder());
			}

			// Create request
			
			director.constructRequest(in, path);
			Request request = director.getRequest();
			
			//Append IP address of the connected client to the request object
			request.setIpAddress(socket.getInetAddress().getHostAddress());
			
			// Send request to chain of handlers and get requested resource
			
			chain.handle(chain.getRoot(), request);

			// Create response
					
			Response response = responseDirector.getResponse();
			
			// Send response out
		
			response.writeTo(out);
			
			out.flush();
			in.close();
			inputStreamReader.close();
			socket.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
